package com.bxs.controller;

import com.bxs.global.CommandMsg;
import com.bxs.global.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CommandController {
    @GetMapping("/cmd")
    public Object getCommand(@RequestParam Map<String, Object> param){
        System.out.println(param);
        String cmd = (String)param.get("cmd");
        Socket socket = null;
        Map<String, Object> result = null;
        try {
            socket = new Socket("127.0.0.1", 8989);
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            CommandMsg test = new CommandMsg(cmd);
//            data.put("command", test);
            ObjectMapper objectMapper = new ObjectMapper();
//            outputStream.write(objectMapper.writeValueAsString(test).getBytes(StandardCharsets.UTF_8));
            bufferedWriter.write(objectMapper.writeValueAsString(test));
            bufferedWriter.flush();
            System.out.println("client write finish");
            StringBuffer sb = new StringBuffer();
            int len = 0;
            char buf[] = new char[1024];
            do{
                len = bufferedReader.read(buf, 0, 1024);
                if(len == -1)continue;
                sb.append(buf, 0, len);
            }while(bufferedReader.ready());
            System.out.println("resp: " + sb);
            inputStream.close();
            outputStream.close();
            bufferedWriter.close();
            bufferedReader.close();
//            data.put("resp", sb.toString());
//            System.out.println(sb.toString());
            result = JsonUtils.readFromJson(sb.toString());
            System.out.println("client finished");
        } catch (IOException e) {
            e.printStackTrace();
            return "socket error";
        }
        return result;
    }
}
